const validate = require("validate.js");

const { formatResponse } = require("../utils/tool");
const {
  createBlogTypeDao,
  deleteBlogTypeDao,
  findAllBlogTypeDao,
  findByPkBlogTypeDao,
  updateBlogTypeDao,
} = require("../dao/blogTypeDao");

const { ValidationError } = require("../utils/error");

exports.createBlogTypeService = async (data) => {
  const rules = {
    name: {
      presence: { allowEmpty: false },
      length: { minimum: 2, maximum: 50 },
    },
  };

  const result = validate(data, rules);
  
  if (result) {
    const [key] = Object.keys(result);
    throw new ValidationError(result[key][0]);
  }

  const res = await createBlogTypeDao(data);
  return formatResponse(0, "", res.dataValues);
};

exports.deleteBlogTypeService = async (id) => {
  const res = await deleteBlogTypeDao(id);
  if (!res) throw new ValidationError("blogType is not exist");
  return formatResponse(0, "", null);
};

exports.findAllBlogTypeService = async () => {
  return await findAllBlogTypeDao();
};

exports.updateBlogTypeService = async (id, data) => {
  await updateBlogTypeDao(id, data);
  return formatResponse(0, "", null);
};

exports.findByIdBlogTypeService = async (id) => {
  const res = await findByPkBlogTypeDao(id);
  if (res) return formatResponse(0, "", res.dataValues);
  if (!res) throw new ValidationError("blogType is not exist");
};
